import utils from './index.js'
// Utility functions for both paths and points

// @shp An element of the layer.shapes array
//   (may be null, or, depending on layer type, an array of points or an array of arrays of arc ids)
function cloneShape(shp) {
  if (!shp) return null
  return shp.map((part) => {
    return part.concat()
  })
}
function cloneShapes(arr) {
  return utils.isArray(arr) ? arr.map(cloneShape) : null
}
function forEachShapePart(paths, cb) {
  editShapeParts(paths, cb)
}
function editShapeParts(parts, cb) {
  if (!parts) return null // null geometry not edited
  if (!utils.isArray(parts)) utils.error("Expected an array, received:", parts)
  let nulls = 0
  const n = parts.length
  let retn = null

  for (let i=0; i<n; i++) {
    retn = cb(parts[i], i, parts)
    if (retn === null) {
      nulls++
      parts[i] = null
    } else if (utils.isArray(retn)) {
      parts[i] = retn
    }
  }
  if (nulls == n) {
    return null
  } else if (nulls > 0) {
    return parts.filter((part) => {return !!part})
  } else {
    return parts
  }
}
// Get max number of parts in a single shape from an array of shapes.
// Caveat: polygon holes are counted as separate parts.
function findMaxPartCount(shapes) {
  let maxCount = 0
  for (let i=0, n=shapes.length; i<n; i++) {
    const shp = shapes[i]
    if (shp && shp.length > maxCount) {
      maxCount = shp.length
    }
  }
  return maxCount
}
export default {
  forEachShapePart,
  editShapeParts,
  cloneShape,
  cloneShapes,
  findMaxPartCount,
}